package com.zzyy.study;


import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car
{
    int saleTotal;
    public synchronized void sale()
    {
        saleTotal++;
    }

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
    public void saleWithThreadLocal()
    {
        threadLocal.set(1 + threadLocal.get());
    }
}


/**
 * @auther zzyy
 * @create 2024-04-19 17:34
 */
public class ThreadLocalDemo
{
    public static void main(String[] args)
    {
        Car car = new Car();

        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= new Random().nextInt(2) + 1; j++) {
                        car.sale();
                        car.saleWithThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t" + "号销售卖出：" + car.threadLocal.get());
                } finally {
                    car.threadLocal.remove();
                }
            }, String.valueOf(i)).start();
        }
        //暂停毫秒
        try {
            TimeUnit.MILLISECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t" + "销售总数: " + car.saleTotal);
    }
}
